<template>
  <div class="commerce">
    <LlNavBar
      v-if="showNavbar"
      title="添加商机"
      :left-click="() => $emit('cancel')"
    />
    <div class="commerce-form">
      <LlForm ref="form" title="添加商机">
        <LlFormItem
          label="商机名称"
          filed="name"
          :value="form.name"
          :rules="[
            {
              required: true,
              message: '请输入商机名称',
              validator: _businessName,
            },
          ]"
          :show-arrow="false"
        >
          <Field
            v-model="form.name"
            class="!p-0"
            placeholder="请输入商机名称"
          />
        </LlFormItem>
        <LlFormItem
          label="KP称呼"
          filed="kpName"
          :value="form.kpName"
          :rules="[{ required: true, message: '请输入KP称呼' }]"
          :show-arrow="false"
        >
          <Field
            v-model="form.kpName"
            class="!p-0"
            placeholder="请输入KP称呼"
          />
        </LlFormItem>
        <LlFormItem
          label="KP职位"
          filed="positionName"
          :value="form.positionName"
          :rules="[{ required: true, message: '请选择KP职位' }]"
          @click="() => (showKpPosition = true)"
        />

        <LlFormItem
          label="KP手机号"
          filed="phone"
          :value="form.phone"
          :rules="[
            {
              validator: _validator,
              message: '手机号、微信、座机至少填写一个',
            },
            {
              validator: _validatorPhone,
              message: '手机号格式错误',
            },
          ]"
          :show-arrow="false"
        >
          <Field
            v-model="form.phone"
            class="!p-0"
            placeholder="请输入KP手机号"
          />
        </LlFormItem>
        <LlFormItem
          label="KP微信"
          filed="wechat"
          :value="form.wechat"
          :rules="[
            {
              validator: _validator,
              message: '手机号、微信、座机至少填写一个',
            },
          ]"
          :show-arrow="false"
        >
          <Field
            v-model="form.wechat"
            class="!p-0"
            placeholder="请输入KP微信"
          />
        </LlFormItem>
        <LlFormItem
          label="KP座机"
          filed="landline"
          :value="form.landline"
          :rules="[
            {
              validator: _validator,
              message: '手机号、微信、座机至少填写一个',
            },
          ]"
          :show-arrow="false"
        >
          <Field
            v-model="form.landline"
            class="!p-0"
            placeholder="请输入KP座机"
          />
        </LlFormItem>

        <LlFormItem
          label="品类"
          filed="categoryName"
          :value="form.categoryName"
          :rules="[{ required: true, message: '请选择品类' }]"
          placehoder="请选择"
          @click="() => (showCategory = true)"
        />

        <LlFormItem
          label="地址"
          filed="address"
          :value="form.address"
          placehoder="请选择"
          :rules="[{ required: true, message: '请选择地址' }]"
          @click="() => (showVisitLocation = true)"
        >
          <template #icon>
            <Icon :name="LocationIcon" />
          </template>
        </LlFormItem>

        <LlFormItem
          label="店铺名称"
          filed="storeName"
          :value="form.storeName"
          :rules="[{ required: true, message: '请输入店铺名称' }]"
          :show-arrow="false"
        >
          <Field
            v-model="form.storeName"
            class="!p-0"
            placeholder="请输入店铺名称"
          />
        </LlFormItem>

        <LlFormItem
          label="高德POI"
          filed="poi"
          :value="form.poi"
          placehoder="选择地址后自动获取"
          :show-arrow="false"
        />

        <LlFormItem
          v-if="showUploader"
          label="门店门头照片"
          :show-arrow="false"
        >
          <LlUploader
            v-model="photoList"
            @change="_onUploadChange"
            :capture="['camera']"
          />
        </LlFormItem>
      </LlForm>
    </div>
    <div class="commerce-footer">
      <Button
        class="flex-1 !rounded-10px"
        @click="() => $emit('cancel')"
        plain
        type="primary"
      >
        取消
      </Button>
      <Button
        @click="handleSave"
        :loading="loading"
        class="flex-1 !ml-9px !rounded-10px"
        type="primary"
      >
        新增
      </Button>
    </div>
    <div class="add__business">
      <!-- KP职位 -->
      <Popup
        v-model="showKpPosition"
        safe-area-inset-bottom
        round
        position="bottom"
      >
        <span class="title">KP职位</span>
        <Picker
          :columns="kpPositionOptions"
          show-toolbar
          @cancel="showKpPosition = false"
          @confirm="_kpPositionSelect"
          toolbar-position="bottom"
          swipe-duration="100"
        />
      </Popup>
    </div>
    <div class="add__business">
      <!-- 品类 -->
      <Popup
        v-model="showCategory"
        round
        safe-area-inset-bottom
        position="bottom"
      >
        <span class="title">品类</span>
        <Picker
          :columns="categoryOptions"
          show-toolbar
          @cancel="showCategory = false"
          @confirm="_categoryConfirm"
          toolbar-position="bottom"
          swipe-duration="100"
        />
      </Popup>
    </div>

    <!-- 拜访地点 -->
    <Popup v-model="showVisitLocation" position="right">
      <LlMap
        v-if="showVisitLocation"
        @cancel="showVisitLocation = false"
        @confirm="_mapConfirm"
        type="search"
      />
    </Popup>
  </div>
</template>

<script>
import _ from "lodash";
import { Toast, Icon, Field, Button, Popup, Picker } from "vant";
import LlNavBar from "@/components/ll-nav-bar";
import LlForm from "@/components/ll-form";
import LlFormItem from "@/components/ll-form-item";
import LlMap from "@/components/ll-map";
import LlUploader from "@/components/ll-uploader";
import LocationIcon from "@/assets/icon/location.png";
import { fetchDictOptions, fetchProductCategory } from "@/services";

export default {
  components: {
    Icon,
    Field,
    Button,
    Popup,
    Picker,
    LlNavBar,
    LlForm,
    LlFormItem,
    LlMap,
    LlUploader,
  },
  props: {
    showNavbar: {
      type: Boolean,
      default: true,
    },
    showUploader: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      LocationIcon,
      loading: false,
      form: {
        dataSource: this.showUploader ? 1 : 2,
        name: null, // 商机名称
        kpName: null, // kp名称
        position: null, // 职位
        positionName: null, // 职位名称
        phone: null,
        landline: null,
        wechat: null,
        categoryOne: null, // 一级品类
        categoryTwo: null,
        categoryThree: null,
        categoryName: null,
        poi: null,
        // poiName: null,
        // latitude: null,
        // longitude: null,
        // province: null, // 省
        // provinceCode: null,
        // city: null, // 市
        // cityCode: null, // 城市code
        // district: null, // 区
        // districtCode: null,
        address: null,
        storeName: null, // 店铺名称
        addOpportunityFileReqs: [],
      },
      showKpPosition: false, // kp职位
      kpPositionOptions: [],
      showCategory: false, // 品类
      categoryOptions: [],
      showVisitLocation: false, // 拜访地点
      photoList: [],
    };
  },
  created() {
    this._initOptions();
  },
  methods: {
    async _initOptions() {
      try {
        await this._initKpPositionOptions();
        await this._initProductCategoryOptions();
      } catch (error) {
        Toast("初始化数据失败");
      }
    },
    /**
     * 获取kp职位
     */
    async _initKpPositionOptions() {
      try {
        const result = await fetchDictOptions("kp_position");
        this.kpPositionOptions = result.map(({ name, type }) => ({
          text: name,
          key: type,
        }));
      } catch (error) {
        Toast("获取kp职位失败");
      }
    },
    /**
     * 获取产品品类
     */
    async _initProductCategoryOptions() {
      try {
        const result = await fetchProductCategory();
        const _getColumns = (arr) => {
          return arr.map(({ id, name, children }) => {
            return {
              text: name,
              key: id,
              ...(children && children.length
                ? { children: _getColumns(children) }
                : {}),
            };
          });
        };
        this.categoryOptions = _getColumns(result.children);
      } catch (error) {
        Toast("获取产品品类失败");
      }
    },
    handleSave: _.throttle(function () {
      this.$refs.form
        .validate()
        .then(() => {
          const form = { ...this.form };
          if (this.showUploader && form.addOpportunityFileReqs.length === 0) {
            Toast("请上传门店门头照片");
            return;
          }
          this.loading = true;
          this.$emit("confirm", form, () => {
            this.loading = false;
          });
        })
        .catch((e) => {
          Toast(e[0].message);
        });
    }, 500),
    /**
     * kp职位选择
     */
    _kpPositionSelect(val) {
      this.form.position = val.key;
      this.form.positionName = val.text;
      this.$nextTick(() => {
        this.showKpPosition = false;
      });
    },
    /**
     * 品类选择
     */
    _categoryConfirm(val, index) {
      this.form.categoryName = val.join("-");
      this.form.categoryOne = this.categoryOptions[index[0]].key;
      this.form.categoryTwo =
        this.categoryOptions[index[0]].children[index[1]].key;
      this.form.categoryThree =
        this.categoryOptions[index[0]].children[index[1]].children[
          index[2]
        ].key;
      this.$nextTick(() => {
        this.showCategory = false;
      });
    },
    _mapConfirm(poi) {
      this.form.address = `${poi.pname}${poi.cityname}${poi.adname}${poi.address}(${poi.name})`;
      this.form.storeName = poi.name; // 店铺名称
      this.form.poi = poi.id;
      // this.form.poiName = poi.name;
      // this.form.longitude = poi.location.lng; // 经度
      // this.form.latitude = poi.location.lat; // 纬度
      // this.form.province = poi.pname; // 省
      // this.form.provinceCode = poi.pcode;
      // this.form.city = poi.cityname; // 市
      // this.form.cityCode = poi.citycode; // 城市编码
      // this.form.district = poi.adname; // 区
      // this.form.districtCode = poi.adcode;
      this.$nextTick(() => {
        this.showVisitLocation = false;
      });
    },
    _onUploadChange(files) {
      this.form.addOpportunityFileReqs = files
        .filter(({ status }) => status === "done")
        .map(({ fileName, originalName, url, suffix }) => ({
          fileName: originalName,
          url: fileName,
          completeUrl: url,
          suffix,
          type: 1,
        }));
    },
    /**
     * 电话/微信/座机检验
     */
    _validator() {
      const { phone, landline, wechat } = this.form;
      const value = phone || landline || wechat;
      return !!value;
    },
    /**
     * 验证手机格式
     */
    _validatorPhone() {
      const { phone } = this.form;
      const reg = /^1\d{10}$/;
      console.log(phone && reg.test(phone));
      return phone && reg.test(phone);
    },
    /**
     * 验证商机格式
     */
    _businessName() {
      var regStr =
        // eslint-disable-next-line no-misleading-character-class
        /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi;
      this.form.name = this.form.name.replace(regStr, "");
    },
  },
};
</script>

<style lang="scss" scoped>
.commerce {
  @apply h-full overflow-hidden flex flex-col;
  background: #f6f6f6;
  .commerce-form {
    @apply px-10px py-12px  flex-1 overflow-auto;
  }
  .commerce-footer {
    @apply flex items-center pt-10px px-16px bg-white;
    padding-bottom: calc(env(safe-area-inset-bottom) + 10px);
    box-shadow: 0px -2px 6px 0px rgba(164, 170, 183, 0.2);
  }
  .add__business {
    .van-popup {
      padding: 20px 12px 0 12px;
      .title {
        font-size: 16px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #333333;
        margin-bottom: 12px;
      }
      ::v-deep .van-picker__toolbar {
        height: calc(50px + env(safe-area-inset-bottom));
        padding-bottom: env(safe-area-inset-bottom);
        min-height: 50px;
        box-shadow: 0px -1px 1px 0px #f5f5f5;
      }
      ::v-deep .van-picker__cancel,
      ::v-deep .van-picker__confirm {
        flex-grow: 1;
        min-width: 28px;
        height: 20px;
        font-weight: 500;
        text-align: center;
        font-size: 14px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
      }
      ::v-deep .van-picker__cancel {
        color: #666666;
      }
      ::v-deep .van-picker__cancel::after {
        content: "";
        position: absolute;
        display: inline-block;
        width: 1px;
        height: 5.33333vw;
        background: #f0f0f0;
        left: 50%;
      }
      ::v-deep .van-picker__confirm {
        color: #1d6fe9;
      }
      ::v-deep .van-picker-column__item {
        // height: 52px !important;
        .van-ellipsis {
          color: #c5cad5;
          font-size: 14px;
        }
      }
      ::v-deep .van-picker-column {
        margin-bottom: 16px;
      }
      ::v-deep .van-picker-column__item--selected {
        .van-ellipsis {
          color: #1d6fe9;
          font-weight: 500;
        }
      }
    }
  }
}
</style>
